import {
    createAGroupFolder,
    getPlayerData,
    isGroupExist,
    isPlayerExist,
    storagePlayerData,
    getConfig,
    ensureGroupAndPlayerExist
} from "../function/function.js";

export class BuyBackSelf extends plugin {
    constructor() {
        super({
            name: '[Sm]获取自由',
            dsc: '以2倍身价获取自由，身价变为原来的1.2倍',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/]自由$/, fnc: 'buyBackSelf' }
            ]
        })
    }

    async buyBackSelf(e) {
        try {
            // 读取配置
            const config = getConfig();

            // 检查是否在群组中使用
            if (!e.isGroup) return e.reply(['该功能只能在群内使用']);
            const ID = [e.user_id, e.group_id];

            // 使用通用函数检查和初始化群组和玩家
            ensureGroupAndPlayerExist(ID[1], ID[0]);

            // 获取玩家数据
            const userData = await getPlayerData(ID[1], ID[0]);
            const { currency, value, master } = userData;

            // 如果玩家没有主人，返回提示信息
            if (master === '') return e.reply(['你已经是自由的了']);

            // 计算获取自由价格
            const buyBackPrice = parseInt(parseFloat((value * 2).toFixed(1)));

            // 检查玩家是否有足够的金币获取自由
            if (currency < buyBackPrice) return e.reply([
                segment.at(ID[0]),
                `你买不起自己！需要${buyBackPrice}金币`
            ]);

            // 获取前主人的数据
            const formerOwnerData = await getPlayerData(ID[1], master);
            const memberInfoList = Object.fromEntries([...await Bot.pickGroup(ID[1]).getMemberMap()]);

            // 增加获取自由冷却时间和次数限制
            const currentSecond = Math.floor(Date.now() / 1000);
            const buyBackCooldown = config.buyBack.cooldown; // 从配置文件读取冷却时间
            const maxBuyBackTimes = config.buyBack.maxTimes; // 从配置文件读取最大获取自由次数

            if (userData.buyBackTimes >= maxBuyBackTimes) {
                return e.reply(['本周获取自由次数已达上限，请下周再试。']);
            }

            if (currentSecond - userData.lastBuyBackTime < buyBackCooldown) {
                const remainingTime = buyBackCooldown - (currentSecond - userData.lastBuyBackTime);
                return e.reply([`获取自由冷却中，剩余时间：${Math.floor(remainingTime / 3600)}小时${Math.floor((remainingTime % 3600) / 60)}分钟`]);
            }

            // 更新玩家数据：扣除金币，更新身价，清空主人
            userData['currency'] = parseFloat((parseInt(userData['currency']) - buyBackPrice).toFixed(1));
            userData['value'] = parseFloat((value * 1.2).toFixed(1));
            userData['master'] = '';
            storagePlayerData(ID[1], ID[0], userData);

            // 更新前主人的数据：增加金币，移除奴隶
            formerOwnerData['currency'] = parseFloat((formerOwnerData['currency'] + buyBackPrice).toFixed(1));
            formerOwnerData['slave'] = formerOwnerData['slave'].filter(a => a !== ID[0]);
            storagePlayerData(ID[1], master, formerOwnerData);

            // 更新获取自由时间和次数
            userData.lastBuyBackTime = currentSecond;
            userData.buyBackTimes = (userData.buyBackTimes || 0) + 1;

            // 增加税收机制
            const taxRate = config.buyBack.taxRate; // 从配置文件读取税率
            const taxAmount = parseFloat((userData.currency * taxRate).toFixed(1));
            userData.currency -= taxAmount;
            storagePlayerData(ID[1], ID[0], userData);
            await e.reply([`你支付了${taxAmount}金币的税收。`]);

            // 返回成功信息
            return e.reply([`成功支付${buyBackPrice}金币获得自由！现在你的身价是${userData['value']}金币\n${memberInfoList[master]['nickname']}获得了${buyBackPrice}金币，现在拥有${formerOwnerData['currency']}金币。\n你现在拥有${userData['currency']}金币。`]);
        } catch (error) {
            // 处理错误
            logger.error('处理获取自由请求时出错:', error);
            return e.reply(['处理请求时出错，请稍后再试。']);
        }
    }
}
